const { defineComponent } = require('san/san')

const imgUrl = __uri('/assets/imgs/failview.png')

const FailView = defineComponent({
    template: `
        <template>
            <div s-if="isFail" class="s-fail-view" >
                <div class="fail-view-table">
                <div class="fail-view-ctn">
                    <div class="fail-view-box" style="display: {{ height < 130 ? 'inline-block' : 'block' }}">
                        <img class="fail-view-img" src="${ imgUrl }" style="width: {{ imgWidth }}px"/>
                    </div>
                    <div class="fail-view-tip">
                        {{ opt.errMsg || '请求失败, 试试看刷新页面' }}
                        <button class="fail-view-btn" on-click="touch">{{ opt.btnText || '重新选择' }}</button>
                    </div>
                </div>
                </div>
            </div>
        </template>
    `,
    inited () {
        this.watch('isFail', v => {
            const $parent = $(this.el).parent()
            if (!v) {
                let position = this.data.get('position')
                if (!position) return
                $parent.css('position', position)
            } else {
                this.data.set('position', 'relative')
                $parent.css('position', 'relative')
            }
        })
    },
    attached () {
        let $el = $(this.el)
        let $parent = $el.parent()
        let position = $parent.css('position')
        this.data.set('position', position)
        $parent.css('position', 'relative')

        this.nextTick(() => {
            const height = parseInt($parent.css('height')) + 4
            const width = height * 0.48
            this.data.set('imgWidth', width)
            this.data.set('height', height)
        })
    },
    initData () {
        return {
            position: '',
            isFail: true,
            height: 100
        }
    },
    touch () {
        let position = this.data.get('position')
        $(this.el).parent().css('position', position)
        this.data.set('isFail', false)
        this.fire('retry')
    }
})

module.exports = FailView